import { fromString, place, Position } from '@feidao-factory/core/dom';
import { IFeidaoAiBrowserComponent } from '../../interfaces';
import lazyload_picture from '../lazyload/picture';
import data_render from './data-render';


/**
 * 渲染
 * @param fd 系统变量
 * @param data 要渲染的数据
 * @param tpl 渲染片段tpl
 * @param panme p块的名称
 * @param position 'after' | 'before' | 'firstin' | 'lastin' | 'replace' | 'inner'` 渲染位置
 * @example render(fd,data,tpl,panme,position);
 */
export default function render(fd: IFeidaoAiBrowserComponent, data: any, tpl: string, panme: string, position: 'after' | 'before' | 'firstin' | 'lastin' | 'replace' | 'inner') {
	const dom_node = fd.data.node;
	const doms = dom_node.querySelectorAll('[data-feidao-presentation=' + panme + ']') || dom_node.querySelectorAll('[data-feidao-id=' + panme + ']');
	const tpl_d = data_render(data, tpl);
	const list = Array.from(doms);

	if (list.length === 0) {
		throw new Error('cannot find node: ' + panme);
	}
	if (position === 'inner') {
		// destory_lazyload_picture(dom);//之前测试的时候ie8不清除绑定的事件会出错
		list.forEach((dom) => {
			const node = fromString(tpl_d || '');
			fd.parse_event(node);
			dom.innerHTML = '';
			dom.appendChild(node);
		});
	} else if (position !== undefined && position !== null) {
		list.forEach((dom) => {
			const node = fromString(tpl_d || '');
			fd.parse_event(node as any);
			place(node, (() => {
				switch (position) {
					case 'replace':
						return Position.Replace;
					case 'after':
						return Position.After;
					case 'before':
						return Position.Before;
					case 'firstin':
						return Position.FirstIn;
					case 'lastin':
					default:
						return Position.LastIn;
				}
			})(), dom);
		});
	} else {
		list.forEach((dom) => {
			// destory_lazyload_picture(dom);//之前测试的时候ie8不清除绑定的事件会出错
			const node = fromString(tpl_d || '');
			fd.parse_event(node as any);
			dom.innerHTML = '';
			dom.appendChild(node);
		});
	}
	list.forEach((dom) => {
		lazyload_picture(dom);
	});
}
